package com.study.server.codec;

import com.study.server.message.AbstractMessage;
import com.study.server.message.GameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by meen on 2017/12/4.
 */
public class MessageEncoder extends MessageToByteEncoder<AbstractMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, AbstractMessage msg, ByteBuf out) throws Exception {
        if (msg instanceof GameMessage) {
            //头长:HEAD(2bytes) + length(int) + cmdId(short)
            int headLen = GameMessage.HEAD.length + Short.SIZE / Byte.SIZE + Integer.SIZE / Byte.SIZE;
            int length = headLen + msg.remaining();
            ByteBuf buf = UnpooledByteBufAllocator.DEFAULT.directBuffer(length);
            buf.writeBytes(GameMessage.HEAD);
            buf.writeInt(length);
            buf.writeShort(msg.getCmdId());
            buf.writeBytes(((GameMessage) msg).getContent());
            out.writeBytes(buf);
        }
    }
}
